import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.List;
import java.util.stream.Collectors;

public class Task {

    public static void main(String[] args) throws DocumentException {
        Order order = parseOrder("lesson10/task4/src/data.xml");
        System.out.println(order);
    }

    /**
     * 解析订单数据
     *
     * @param filePath 订单数据文件路径
     * @return 订单对象
     */
    public static Order parseOrder(String filePath) throws DocumentException {
        // 创建解析器
        SAXReader reader = new SAXReader();
        // 解析XML文件
        Document document = reader.read(new File(filePath));
        // 获取根节点
        Element rootElement = document.getRootElement();

        Order order = new Order();
        // 获取订单ID
        order.setId(rootElement.elementText("id"));
        // 获取订单日期
        order.setDate(rootElement.elementText("date"));
        // 获取收货人信息
        Element receiverElement = rootElement.element("receiver");
        Receiver receiver = new Receiver(
                receiverElement.elementText("name"),
                receiverElement.elementText("address")
        );
        order.setReceiver(receiver);
        // 获取商品列表
        final List<Element> elements = rootElement.element("items").elements();
        final List<Item> items = elements.stream().map(element ->
                new Item (
                        element.elementText("name"),
                        Integer.parseInt(element.elementText("quantity")),
                        Double.parseDouble(element.elementText("price"))
                )
        ).collect(Collectors.toList());

        order.setItems(items);

        // 获取备注
        order.setRemarks(rootElement.elementTextTrim("remarks"));
        return order;
    }

}